﻿using System;
using System.Xml;

namespace BuzzX8.Xmpp.StreamElements.Stanza
{
    public class MessageStanza : Stanza<MessageStanzaType>
    {
        public MessageStanza() : base("message")
        {
        }

        public string Subject { get; set; }

        public string Body { get; set; }

        public object ParentThreadId { get; set; }

        public object ThreadId { get; set; }

        protected override void WritePayload(XmlWriter writer)
        {
            base.WritePayload(writer);
            WriteSubject(writer);
            WriteBody(writer);
            WriteThreadId(writer);
        }

        private void WriteSubject(XmlWriter writer)
        {
            if (!string.IsNullOrEmpty(Subject)) writer.WriteElementString("subject", Subject);
        }

        private void WriteBody(XmlWriter writer)
        {
            if (!string.IsNullOrEmpty(Body)) writer.WriteElementString("body", Body);
        }

        private void WriteThreadId(XmlWriter writer)
        {
            string threadIdValue = ThreadId == null ? "" : ThreadId.ToString();
            string parentThreadIdValue = ParentThreadId == null ? "" : ParentThreadId.ToString();
            if (string.IsNullOrEmpty(threadIdValue)) return;
            writer.WriteStartElement("thread");
            if (!string.IsNullOrEmpty(parentThreadIdValue)) writer.WriteAttributeString("parent", parentThreadIdValue);
            writer.WriteString(threadIdValue);
            writer.WriteEndElement();
        }

        protected override object GetAttributeValueForType(MessageStanzaType type)
        {
            switch (type)
            {
                case MessageStanzaType.None:
                    return "";

                case MessageStanzaType.Chat:
                    return "chat";

                case MessageStanzaType.Normal:
                    return "normal";

                case MessageStanzaType.GroupChat:
                    return "groupchat";

                case MessageStanzaType.Headline:
                    return "headline";

                case MessageStanzaType.Error:
                    return "error";

                default:
                    throw new NotImplementedException();
            }
        }
    }
}
